using System.Collections.Generic;
using UnityEngine;

public class HttpWebRequestDownloadQueue
{
    // 最大同时下载数量
    private Queue<BackGroundDownloadParam> m_DownloadQueue;
    private HashSet<HttpWebRequestDownloader> m_DownloadingSet = new HashSet<HttpWebRequestDownloader>();
    private int m_FinishCount;
    
    public HttpWebRequestDownloadQueue(Queue<BackGroundDownloadParam> downloadDownloadQueue)
    {
        m_DownloadQueue = downloadDownloadQueue;
    }

    public void StartDownload()
    {
        Debug.Log("[HttpWebRequestDownloadQueue](StartDownload)");
        FillDownloading();
    }

    private void FillDownloading()
    {
        while (m_DownloadQueue.Count > 0 && m_DownloadingSet.Count < NetWorkDefine.s_MaxDownloadingCount)
        {
            var downloader = new HttpWebRequestDownloader(OnDownlaoderComplete);
            m_DownloadingSet.Add(downloader);
            
            var param = m_DownloadQueue.Dequeue();
            var url = NetWorkDefine.k_Url + param.UrlRelativePath;
            var savePath = NetWorkDefine.s_PersistentDataPath + param.SaveRelativePath;
            downloader.Start(url, savePath);
        }
    }

    private void OnDownlaoderComplete(HttpWebRequestDownloader downloader)
    {
        m_FinishCount++;
        m_DownloadingSet.Remove(downloader);
        FillDownloading();
        Logger.Log($"[HttpWebRequestDownloadQueue](OnDownlaoderComplete) m_FinishCount:{m_FinishCount}");

        if (m_DownloadQueue.Count == 0 && m_DownloadingSet.Count == 0)
        {
            Debug.Log($"HttpWebRequestDownloadQueue](OnDownlaoderComplete) Finish all:{m_FinishCount}");
        }
    }
}